<template>
  <div>
    <!-- 一级表示能否访问这个页面，二级表示能否使用这个权限 -->
    <!-- 1. show-checkbox 显示选择框
    2. default-expand-all 默认展开
    3. check-strictly  设置true，可以关闭父子关联 -->
    <el-tree
      ref="tree"
      :data="list"
      :props="{label:'name'}"
      :show-checkbox="true"
      default-expand-all
      :check-strictly="true"
      node-key="id"
    />
    <div style="text-align: right">
      <el-button size="small" type="primary" @click="hSubmit">确定</el-button>
      <el-button size="small" type="danger" @click="hCancel">取消</el-button>
    </div>
  </div>
</template>

<script>
import { tree2 } from '@/utils/tree'
import { getRoleDetail, assignPerm } from '@/api/setting'
import { getPermissionList } from '@/api/permission'
export default {
  name: 'AssignPermission',
  props: {
    curid: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      list: [] // 获取到的权限树状列表
    }
  },
  created() {
    this.loadPermissionList()
    this.loadRoleDetail()
  },
  methods: {
    hCancel() {
      this.$emit('close')
    },
    // 点击了确定
    async hSubmit() {
      const permIds = this.$refs.tree.getCheckedKeys()
      // console.log('当前选中的节点数组是', permIds)
      await assignPerm({
        id: this.curid, // 角色id
        permIds // 权限id
      })
      // 提示
      this.$message.success('保存角色的权限成功')
      // 关闭弹层
      this.hCancel()
    },
    // 获取权限列表
    async loadPermissionList() {
      try {
        const { data } = await getPermissionList()
        this.list = tree2(data)
      } catch (err) {
        console.log(err)
      }
    },
    // 根据id获取权限
    async loadRoleDetail() {
      try {
        const { data } = await getRoleDetail(this.curid)
        // 找到树状组件中让其默认选中
        this.$refs.tree.setCheckedKeys(data.permIds)
      } catch (err) {
        console.log(err)
      }
    }
  }
}
</script>
